<?php

namespace app\one_wxopen\admin;

use app\system\admin\Admin;
use app\one_wxopen\service\WeTool;

class Wemini extends Admin
{
    protected function initialize()
    {
        parent::initialize();
        $tabData['column'] = [
            [
                'label' => '模板库',
                'name' => 'template',
                'url'   => url('one_wxopen/wemini/template'),
            ],
            [
                'label' => '草稿箱',
                'name' => 'draft',
                'url'   => url('one_wxopen/wemini/draft'),
            ],
        ];

        $this->TabData = $tabData;
    }
    public function template($template_id = 0)
    {
        $open =  WeTool::service();
        if ($this->request->isAjax()) {
            //删除指定小程序代码模版
            try {
                $result = $open->deleteTemplate($template_id);
                if ($result['errcode'] != 0) {
                    return $this->error('删除失败,错误代码：' . $result['errcode'] . '错误说明：' . $result['errmsg'], 'wxapp.template/draft');
                }
                goto end;
            } catch (\Exception $e) {
                var_dump($e);
                return $this->error('删除失败'.$e->getMessage());
            }
            end:
            return $this->success('删除成功');
            
        }
        try {
            $result = $open->getTemplateList();
        } catch (\Exception $e) {
            $result['errcode'] = 0;
            $result['template_list'] = [];
        }

        if ($result['errcode'] != 0) {
            return $this->error('未发布，或第三方参数错误', 'setting/index');
        }
        $table_data = $result['template_list'];
        $tab_data            = $this->TabData;
        $tab_data['current'] = 'template';
        return $this->fetch('template', compact('table_data', 'tab_data'));
    }
    public function draft($draft_id = 0)
    {
        $open =  WeTool::service();
        if ($this->request->isAjax()) {
            //把草稿添加到模板库
            try {
                $result = $open->addToTemplate($draft_id);
                if ($result['errcode'] != 0) {
                    return $this->error('添加失败,错误代码：' . $result['errcode'] . '错误说明：' . $result['errmsg'], 'wxapp.template/draft');
                }
                goto end;
            } catch (\Exception $e) {
                return $this->error('添加失败'.$e->getMessage());
            }
            end:
            return $this->success('添加成功');
            
        }

        //显示草稿模板列表
        try {
            $rs = $open->getTemplateDraftList();
        } catch (\Exception $e) {
            $rs['draft_list'] = [];
        }
        $table_data = $rs['draft_list'];
        $tab_data            = $this->TabData;
        $tab_data['current'] = 'draft';
        return $this->fetch('draft', compact('table_data', 'tab_data'));
    }
}
